<template>
  <div class="box color-white">
    <el-row class="mb-14" type="flex" justify="space-between">
      <el-col>
        <el-button
          @click="toUpload"
          class="bg-color font-w"
          icon="el-icon-upload2"
          type="primary"
          >上 传 录 音</el-button
        >
      </el-col>
      <el-col :span="6">
        <el-input @input="getList(fileName)" placeholder="搜索" v-model="fileName">
          <i slot="prefix" class="el-input__icon el-icon-search"></i>
        </el-input>
      </el-col>
    </el-row>
    <Table
      ref="table"
      :highLightCurrentRow="true"
      :tableData="tableList"
      :configData="colConfigList"
    >
      <!-- v-loading="listLoading" -->
      <el-table-column slot="filename" align="center" label="文件名称">
        <template slot-scope="scope">
          <div title="进入详情" style="color: aqua" class="text-l font-16">
            {{ scope.row.filename }}
          </div>
        </template>
      </el-table-column>
      <el-table-column slot="progress" align="center" label="状态">
        <template slot-scope="scope">
          <div
            v-if="scope.row.progress == '提取完成'"
            style="justify-content: center"
            class="d-flex"
          >
            <img class="mr-5" src="../../assets/intelligence/完成.png" alt="" />
            <span>已完成</span>
          </div>

          <div v-else>
            <p class="text-l">转换中 - 剩余时间:{{ scope.row.time }}</p>
            <div style="width: 100%">
              <el-progress
                :percentage="scope.row.percent"
                :show-text="false"
              ></el-progress>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column
        slot="operation"
        align="center"
        fixed="right"
        label="操作"
        width="140"
      >
        <template slot-scope="scope">
          <el-button
            @click="toRecordDetail(scope.row)"
            title="查看"
            class="fonts-20"
            icon="el-icon-view"
            type="text"
          ></el-button>
          <el-button
            @click="downloadRecord(scope.row)"
            title="下载"
            class="fonts-20"
            icon="el-icon-download"
            type="text"
          ></el-button>
          <el-button
            @click="delRecord(scope.row.id)"
            title="删除"
            class="fonts-20"
            icon="el-icon-delete"
            type="text"
          ></el-button>
        </template>
      </el-table-column>
    </Table>
    <el-dialog
      custom-class="historyModal"
      :close-on-click-modal="false"
      :show-close="false"
      :close-on-press-escape="false"
      width="40%"
      :visible.sync="uploadModal.Visible"
    >
      <el-row slot="title">
        <div class="history-title">上传本地音频文件</div>
      </el-row>
      <el-row class="mb-10">
        <el-upload
          drag
          multiple
          :file-list="fileMeetingList"
          :auto-upload="false"
          :on-change="uploadVectorChange"
          :show-file-list="true"
          action="#"
        >
          <img
            class="mb-10"
            style="margin-top: 40px"
            src="../../assets/intelligence/上传logo.png"
            alt=""
          />
          <div class="color-white">
            将音频文件拖到此处区域 / <span class="color-013f70">文件上传</span>
          </div>
        </el-upload>
      </el-row>
      <el-row class="mb-10 color-white">
        <p>● 支持的音频格式：wav，mp3，m4a， mp4，avi，mpeg</p>
        <p>● 单次最多可上传5个文件</p>
      </el-row>
      <el-row class="text-r">
        <el-button @click="transPort" size="small" class="btn bg-color"
          >开始导入</el-button
        >
        <el-button @click="cancelUpload" size="small" class="btn bg-color"
          >取消</el-button
        >
      </el-row>
    </el-dialog>
  </div>
</template>
<script>
import axios from "axios";
import Table from "@/components/YDL_Table";
import { Loading } from "element-ui";
export default {
  components: {
    Table,
  },
  name: "home",
  data() {
    return {
      uploadModal: {
        Visible: false,
      },
      fileMeetingList: [],
      meetinguid: null,
      fileName: "",
      listLoading: false,
      tableList: [
        // {
        //   id: 1,
        //   username: 'XXX会议讲话录音',
        //   deptname: 1,
        //   rolename: '00:08:00',
        //   createtime: '2023-01-09 15:00:00',
        // },
        // {
        //   id: 2,
        //   username: 'XXX会议讲话录音',
        //   deptname: 0,
        //   rolename: '00:08:00',
        //   createtime: '2023-01-09 15:00:00',
        // },
        // {
        //   id: 4,
        //   username: 'XXX会议讲话录音',
        //   deptname: 1,
        //   rolename: '00:08:00',
        //   createtime: '2023-01-09 15:00:00',
        // },
        // {
        //   id: 3,
        //   username: 'XXX会议讲话录音',
        //   deptname: 0,
        //   rolename: '00:08:00',
        //   createtime: '2023-01-09 15:00:00',
        // },
      ],
    };
  },
  computed: {
    colConfigList() {
      return [
        {
          label: "序号",
          type: "index",
          fixed: "left",
          width: "60",
        },

        {
          label: "文件名称",
          slot: "filename",
        },
        {
          label: "状态",
          slot: "progress",
        },
        {
          label: "时长",
          prop: "duration",
        },
        {
          label: "创建时间",
          prop: "uploadtime",
        },

        {
          slot: "operation",
        },
      ];
    },
  },
  mounted() {
    this.getList("");
  },
  methods: {
    // 删除录音文件
    delRecord(id) {
      this.$confirm("是否确认删除该录音文件？", "提示", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning",
        title: "提示",
      }).then(() => {
        axios({
          method: "post",
          url: "/gt/util/delkbfile",
          data: {
            id: id,
          },
        }).then((res) => {
          if (res.data.success === true) {
            this.$message.success("删除文件成功!");
            this.getList("");
          } else {
            this.$message.error("删除文件失败!");
          }
        });
      });
    },
    // 下载录音文件
    downloadRecord(row) {
      const loading = Loading.service({
        fullscreen: true,
        text: "下载中...",
        spinner: "el-icon-loading",
      });
      axios({
        method: "get",
        url: this.BaseApi + `/gt/util/downloadkbfile?fileid=${row.id}`,
        responseType: "blob",
      }).then((res) => {
        loading.close();
        this.$downloadFile(res.data, row.filename);
      });
    },

    // 获取列表接口
    getList(val) {
      // this.listLoading = true
      axios({
        method: "get",
        url: this.BaseApi + `/gt/util/queryaudiolist?filename=${val}`,
      })
        .then((res) => {
          if (res.data.success) {
            res.data.data.forEach((item) => {
              item.duration = this.$convertToTime(item.duration);
            });
            this.tableList = res.data.data;
          } else {
            this.$message.error(res.data.msg);
          }
        })
        .finally(() => {
          // this.listLoading = false
        });
    },
    // 点击进入详情
    toRecordDetail(row) {
      if (row.id) {
        this.$router.push({
          path: `/detail/${row.id}`,
          params: row,
        });
        console.log(row);
        localStorage.setItem("filename", row.filename);
      }
    },
    // 打开上传
    toUpload() {
      this.uploadModal.Visible = true;
      this.meetinguid = this.generateUUID();
      localStorage.setItem("meetinguid", this.meetinguid);
    },
    // 取消上传
    cancelUpload() {
      this.fileMeetingList = [];
      this.meetinguid = null;
      this.uploadModal.Visible = false;
    },
    generateUUID() {
      return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function (c) {
        var r = (Math.random() * 16) | 0,
          v = c === "x" ? r : (r & 0x3) | 0x8;
        return v.toString(16);
      });
    },
    // 上传文件
    uploadVectorChange(file, fileList) {
      file.status = "uploading";
      file.percentage = 0;
      const isLt100MB = file.size / 1024 / 1024 <= 100;
      const allowedFormats = [
        "audio/wav",
        "audio/mp3",
        "audio/m4a",
        "audio/x-m4a",
        "audio/mpeg",
        "audio/avi",
        "video/mp4",
        "video/avi",
        "video/mpeg",
      ];
      const isFormat = allowedFormats.includes(file.raw.type);

      if (fileList.length > 5) {
        this.$message.error("单次最多可上传 5 个文件!");
        fileList.pop();
        return false;
      }
      if (!isLt100MB) {
        this.$message.error("上传的文件大小不能超过 100MB!");
        fileList.pop();
        return false;
      }

      if (!isFormat) {
        this.$message.error("上传的文件格式仅支持 wav, mp3, m4a, mp4, avi, mpeg!");
        fileList.pop();
        return false;
      }

      let formdata = new FormData();
      formdata.append("file", file.raw);
      const config = {
        onUploadProgress: (progressEvent) => {
          file.percentage = Math.round(
            (progressEvent.loaded * 100) / progressEvent.total
          );
          this.$forceUpdate();
        },
      };

      axios({
        method: "post",
        url: `/gt/util/uploadaudiofile?kbid=${localStorage.getItem("meetinguid")}`,
        data: formdata,
        ...config,
      }).then((res) => {
        if (res.data.success) {
          file.status = "success";
          file.percentage = 100;
          this.$message({
            showClose: true,
            message: "上传文件成功!",
            type: "success",
          });
          this.fileMeetingList = fileList;
        } else {
          file.status = "error";
          this.$message({
            showClose: true,
            message: "上传文件失败!",
            type: "error",
          });
          this.fileMeetingList = [];
        }
      });
      return true;
    },
    // 开始导入
    transPort() {
      if (this.fileMeetingList.length == 0) {
        this.$message({
          showClose: true,
          message: "请先上传文件!",
          type: "warning",
        });
        return;
      }
      axios({
        method: "post",
        url: `/gt/util/startaudiotranscriber`,
      }).then((res) => {
        if (res.data.success) {
          this.cancelUpload();
          this.$message({
            showClose: true,
            message: "导入成功!",
            type: "success",
          });
          // 轮循调用
          let meetingTimer = setInterval(() => {
            // 调用提取状态接口
            axios({
              method: "get",
              url: this.BaseApi + `/gt/util/queryaudiolist?filename=`,
            }).then((res) => {
              if (res.data.success == true) {
                const newArray = res.data.data.map((item) => {
                  item.duration = this.$convertToTime(item.duration);
                  if (item.percent) {
                    item.percent = parseInt(item.percent.replace("%", ""), 10);
                  } else {
                    item.percent = 0;
                  }
                  if (item.progress === "提取完成") {
                    item.percent = 100;
                  }
                  let time = 0;
                  if (item.percent > 0 && item.percent < 100) {
                    // 假设已经用了 100 秒（这里可以根据实际情况修改已用时间）
                    const elapsedTime = 100;
                    time = (elapsedTime / item.percent) * (100 - item.percent);
                  }
                  const formattedTime = this.formatTime(time);
                  return {
                    ...item,
                    time: formattedTime,
                  };
                });
                this.tableList = newArray;
                const statusFinish = this.tableList.every(
                  (item) => item.progress == "提取完成"
                );
                const statusFail = this.tableList.every(
                  (item) => item.progress == "校验失败"
                );
                if (statusFinish || statusFail) {
                  clearInterval(meetingTimer);
                }
              } else {
                this.$message({
                  showClose: true,
                  message: "提取文件失败!",
                  type: "error",
                });
              }
            });
          }, 1000);
        } else {
          this.$message({
            showClose: true,
            message: "导入失败!",
            type: "error",
          });
          this.fileMeetingList = [];
        }
      });
    },
    // 格式化时间
    formatTime(seconds) {
      const h = Math.floor(seconds / 3600);
      const m = Math.floor((seconds % 3600) / 60);
      const s = Math.floor(seconds % 60);
      return `${h.toString().padStart(2, "0")}:${m
        .toString()
        .padStart(2, "0")}:${s.toString().padStart(2, "0")}`;
    },
  },
};
</script>
<style lang="less" scoped>
.box {
  background-color: #020c14;
  padding: 20px;
  min-height: 100vh; // 设置最小高度为屏幕高度
}
/deep/.el-button--text {
  color: #fff;
}
.bg-color {
  background-color: #013f70;
}
.color-013f70 {
  color: #26a9f9;
  font-weight: 600;
}
/deep/.el-input__inner {
  background-color: #020c14;
  border: 1px solid #26a9f9;
  color: #fff;
}
/deep/.el-input__inner:hover,
.el-input__inner:focus {
  border: 1px solid #26a9f9;
}
/deep/.el-button--primary:focus,
.el-button--primary:hover {
  background-color: #013f70;
  border-color: #013f70;
}
/deep/.el-dialog__header {
  padding: 5px 20px;
  background-color: #013f70;
  color: #fff;
  font-size: 18px;
  font-weight: bold;
  opacity: 0.9;
  border: 2px solid #26a9f9;
}
/deep/.el-dialog__body {
  padding: 20px;
  background-color: #020c14;
  border: 1px solid #26a9f9;
}
/deep/.el-upload-dragger {
  background-color: #04223d;
  width: 38vw;
  border: 1px dashed #26a9f9;
}

/deep/ input[type="file"] {
  display: none;
}
.btn {
  background-image: url("../../assets/intelligence/组1.png");
  background-size: 100% 100%;
  background-position: center;
  color: #fff;
  border: none;
  outline: none;
}
/deep/.btn.active.focus,
.btn.active:focus,
.btn.focus,
.btn:active.focus,
.btn:active:focus,
.btn:focus {
  outline: none;
  border: none;
}

/deep/.el-upload-list__item-name {
  color: #fff;
}
/deep/.el-upload-list__item:hover {
  background-color: inherit;
}
/deep/.el-upload-list__item .el-icon-close {
  color: #fff;
}
.highlight-row {
  background-color: #fff; /* 黄色背景 */
}
/deep/.el-loading-mask {
  background-color: transparent !important;
  z-index: 999;
}
</style>
